package com.example.sinoyd.frameapplication.KotlinFrame.Code.UI

import android.content.Intent
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.example.sinoyd.frameapplication.KotlinFrame.Code.DataClass.Task
import com.example.sinoyd.frameapplication.KotlinFrame.Code.db.FormTask
import com.example.sinoyd.frameapplication.KotlinFrame.Code.db.FormTaskFactor
import com.example.sinoyd.frameapplication.KotlinFrame.Frame.Dataclass.gson
import com.example.sinoyd.frameapplication.KotlinFrame.Frame.Uitl.Networkrequestmodel
import com.example.sinoyd.frameapplication.KotlinFrame.UI.BaseActivity
import com.example.sinoyd.frameapplication.R
import com.example.sinoyd.jiaxingywapplication.Myapplication
import com.sinoyd.Code.Until.Networkrequestaddress
import com.sinoyd.Code.Until.SharedPreferencesFactory
import com.sinoyd.Code.Until.showdialog
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.Response
import org.xutils.DbManager
import org.xutils.x


class MainActivity : BaseActivity() {
    var task: Task = Task()
    //更新类
    var myapplication: Myapplication = Myapplication()
    var db: DbManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        db = x.getDb(myapplication.getDaoConfig())
        //监听事件
        setlisteners()
    }

    private fun setlisteners() {
        //版本升级
        uploadversion.setOnClickListener {
            Toast.makeText(this,"版本升级", Toast.LENGTH_LONG).show()

        }
        //更新
        upload.setOnClickListener {
            Toast.makeText(this,"更新", Toast.LENGTH_LONG).show()
        }
        //注销
        cancellation.setOnClickListener {
            //注销用户名密码
            SharedPreferencesFactory.cleardata(this, "LoginId")
            SharedPreferencesFactory.cleardata(this, "Password")
            SharedPreferencesFactory.cleardata(this, "RowGuid")
            startActivity(Intent(this,LoginActivity::class.java))
            finish()
        }
        //签到
        singin.setOnClickListener {
            startActivity(Intent(this,Sign_in_Activity::class.java))
        }
        //任务管理
        taskmanagement.setOnClickListener {
            startActivity(Intent(this,Task_management_Activity::class.java))
        }
        //站点定位
        sitelocation.setOnClickListener {
            startActivity(Intent(this,Site_location_Activity::class.java))
        }
        //监测数据
        monitoringdata.setOnClickListener {
            startActivity(Intent(this,Monitoring_data_Activity::class.java))
        }
        //下载任务
        downloadtask.setOnClickListener {
            downtask()
        }
        //待完成任务
        To_be_completedtask.setOnClickListener {
            //toast("待完成任务")
            //临时测试查看数据库数据


//            toast("数据库中表单因子有" + MyApplication.db.findAll(FormTaskFactor::class.java).size + "条数据")

        }

        //报警信息
        alarminformation.setOnClickListener {
            startActivity(Intent(this,Alarm_information_Activity::class.java))
        }
        //统计分析
        statisticalanalysis.setOnClickListener {
            startActivity(Intent(this,Atatistical_analysis_Activity::class.java))
        }
        //试剂标液配置
        reagentstandardliquidconfiguration.setOnClickListener {
            startActivity(Intent(this,Reagent_reducatant_manager_Activity::class.java))
        }
        //新建临时任务
        newtemporarytasks.setOnClickListener {
            startActivity(Intent(this,New_Temporary_Tasks_Activity::class.java))
        }
    }


    override fun requestSuccess(response: Response, TAG: String) {
        super.requestSuccess(response, TAG)
        when (TAG) {
            "getTask" -> {
                try {
                    if (response.isSuccessful) {
                        task = gson.fromJson(responsestr, Task::class.java)

                        if (task.result == "True") {
                            //保存任务到本地
                            saveformtask(task)
                            //保存任务因子到本地
                            saveformtaskfactor(task)
                            Looper.prepare()
                            Toast.makeText(this,"下载任务成功",Toast.LENGTH_LONG).show()
                            Looper.loop()
                        } else {
                            Looper.prepare()
                            Toast.makeText(this,task.message,Toast.LENGTH_LONG).show()
                            Looper.loop()
                        }


                    } else {
                        Looper.prepare()
                        Toast.makeText(this,"下载任务失败",Toast.LENGTH_LONG).show()
                        Looper.loop()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }


    /**
     * 保存任务到本地【FormTask】
     */
    private fun saveformtask(task: Task) {
        var tasklist: ArrayList<FormTask> = ArrayList()
        for (item in task.task) {
            var tt = FormTask()
            tt.taskCode = item.taskCode//任务编号
            tt.pointName = item.pointName//站点名称
            tt.taskName = item.taskName//任务名称
            tt.formName = item.formName//表单名称
            tt.endTime = item.endTime//完成时间
            tt.taskStatus = item.taskStatus//任务状态
            tt.taskStatusName = "未完成"//任务状态
            tt.taskType = item.taskType//任务类型
            tt.taskTypeName = item.taskTypeName//任务类型
            tt.operationCompany = item.operationCompany//运营公司
            tt.startDate = item.startDate//开始时间
            tt.endDate = item.endDate//计划完成时间
            tt.rowGuid = item.rowGuid//id
            tt.upload = false
            //任务和用户名绑定
            tt.userid = SharedPreferencesFactory.getdata(this, "RowGuid")
            tt.username = item.userName
            tasklist.add(tt)
        }
        try {
            db!!.save(tasklist)
            Log.i("scj", "任务保存成功")
        } catch (e: Exception) {
            e.printStackTrace()
            Log.i("scj", "任务保存失败")
        }
    }

    /**
     * 任务因子存储【FormTaskFactor】saveformtask
     */
    private fun saveformtaskfactor(task: Task) {
        var taskfacotrlist: ArrayList<FormTaskFactor> = ArrayList()
        for (item in task.task) {
            for (it in item.taskData) {
                var ii = FormTaskFactor()
                ii.taskGuid = it.taskGuid
                ii.pollutantCode = it.pollutantCode
                ii.pollutantName = it.pollutantName
                ii.stanLiquidCode = it.stanLiquidCode
                ii.unit = it.unit
                taskfacotrlist.add(ii)
            }
        }
        try {
            db!!.save(taskfacotrlist)
            Log.i("scj", "任务因子保存成功")
        } catch (e: Exception) {
            e.printStackTrace()
            Log.i("scj", "任务因子保存失败")
        }
    }


    /**
     * 下载任务
     */
    fun downtask() {
        showdialog("loadshow")
        var ntrequest = Networkrequestmodel()
        ntrequest.setMethod(Networkrequestmodel.GETREQUEST)
                .settag("getTask")
                .seturl(Networkrequestaddress.URL_Task)
                .addparam("userGuid", SharedPreferencesFactory.getdata(this, "RowGuid"))
                .start(this)
    }

}
